package door.smartlift.top.service;

import com.alibaba.fastjson.JSON;
import door.smartlift.top.common.utils.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import okhttp3.*;

import java.io.IOException;


@Slf4j
public class ChairCmd {

//    private static final String APP_KEY = "pfHsdtg2rASFK84m";
//    private static final String SECRET_KEY = "ooo3Wx9OkLZkwLYaNzgBrh3wTwT1yO0mjuBRAq0PmpAxmG9BFvtQinm1Z7LtELY4";
//
//
//    /**
//     * 构造Basic Auth认证头信息
//     *
//     * @return
//     */
//    public static String getHeader() {
//        String auth = APP_KEY + ":" + SECRET_KEY;
//        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
//        String authHeader = "Basic " + new String(encodedAuth);
//        return authHeader;
//    }

    /**
     * 启动按摩椅
     * *
     */
    public static final String ADD_URL = "";

    /**
     * **
     *
     * @param imei  硬件编号
     * @param high  高电平持续时间 50
     * @param low   低电平持续时间 250
     * @param pulse 脉冲数
     */
    public static void launcherChairs(String imei, int high, int low, int pulse, String orderCode) {
//        try {
//            //创建连接
//            URL url = new URL(ADD_URL);
//            HttpURLConnection connection = (HttpURLConnection) url
//                    .openConnection();
//            connection.setDoOutput(true);
//            connection.setDoInput(true);
//            connection.setRequestMethod("POST");
//            connection.setUseCaches(false);
//            connection.setInstanceFollowRedirects(true);
//            connection.setRequestProperty("Content-Type", "application/json");
//            connection.setRequestProperty("Authorization", getHeader());
//            connection.connect();
//            //POST请求
//            DataOutputStream out = new DataOutputStream(
//                    connection.getOutputStream());
//            JSONObject obj = new JSONObject();
//            obj.put("imei", imei);
//            obj.put("high", high);
//            obj.put("low", low);
//            obj.put("pulse", pulse);
//            out.writeBytes(obj.toString());
//            out.flush();
//            out.close();
//            //读取响应
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    connection.getInputStream()));
//            String lines;
//            StringBuffer sb = new StringBuffer("");
//            while ((lines = reader.readLine()) != null) {
//                lines = new String(lines.getBytes(), "utf-8");
//                sb.append(lines);
//            }
//            System.out.println(sb);
//            connection.disconnect();
//            log.info("设备imei：" + imei + "--》连接成功，设备返回信息：" + sb.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("设备imei:" + imei + "--》连接失败"+e.getMessage(), e.getMessage());
//        }

        try {
            JSONObject obj = new JSONObject();
            obj.put("imei", imei);
            obj.put("high", high);
            obj.put("low", low);
            obj.put("pulse", pulse);

            String result = OkHttpUtil.postJsonParams(ADD_URL, obj.toString());
            log.info("设备imei：" + imei + "--》设备返回信息：" + result);

            com.alibaba.fastjson.JSONObject job = JSON.parseObject(result);
            int code=10;
            code = job.getIntValue("code");

            if(code==0){
                log.info("设备imei：" + imei + "--》命令发送成功：" );

            }else{
                log.info("设备imei：" + imei + "--》命令发送失败，code 非0：" + result);

            }


        }catch (Exception e) {
            e.printStackTrace();
            log.error("设备imei:" + imei + "--》命令发送失败B，异常抓取" + e.getMessage(), e.getMessage());
        }

        log.info("设备imei:" + imei  );



    }

    /**
     * 获取硬件状态
     */
    public static final String ADD_STATUS = "";

    public static String getImeiStatus(String imei) {

        log.info("=====in getImeiStatus===" + imei);

        try {
            JSONObject obj = new JSONObject();
            obj.put("imei", imei);
            String result = OkHttpUtil.postJsonParams(ADD_STATUS, obj.toString());

            log.info("imei :" + imei + " result:" + result + "==");
            com.alibaba.fastjson.JSONObject job = JSON.parseObject(result);
            com.alibaba.fastjson.JSONObject job_data = (com.alibaba.fastjson.JSONObject) job.get("data");
            String status = job_data.getString("status");

            if (status.equals("0")) {
                return "离线";
            }
            if (status.equals("1")) {
                return "在线";
            }
            if (status.equals("4")) {
                return "关机";
            } else {
                return "异常1";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("设备imei:" + imei + "--》获取状态失败", e.getMessage());
            return "异常2";
        }

//        try {
//            //创建连接
//            URL url = new URL(ADD_STATUS);
//            HttpURLConnection connection = (HttpURLConnection) url
//                    .openConnection();
//            connection.setDoOutput(true);
//            connection.setDoInput(true);
//            connection.setRequestMethod("POST");
//            connection.setUseCaches(false);
//            connection.setInstanceFollowRedirects(true);
//            connection.setRequestProperty("Content-Type", "application/json");
//            connection.setRequestProperty("Authorization", getHeader());
//            connection.connect();
//            //POST请求
//            DataOutputStream out = new DataOutputStream(
//                    connection.getOutputStream());
//            JSONObject obj = new JSONObject();
//            obj.put("imei", imei);
//            out.writeBytes(obj.toString());
//            out.flush();
//            out.close();
//            //读取响应
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    connection.getInputStream()));
//            String lines;
//            StringBuffer sb = new StringBuffer("");
//            while ((lines = reader.readLine()) != null) {
//                lines = new String(lines.getBytes(), "utf-8");
//                sb.append(lines);
//            }
//            System.out.println("sb.toString()" + sb.toString());
//            connection.disconnect();
//            com.alibaba.fastjson.JSONObject job = JSON.parseObject(sb.toString());
//            com.alibaba.fastjson.JSONObject job_data = (com.alibaba.fastjson.JSONObject) job.get("data");
//            String status = job_data.getString("status");
//            System.out.println(status);
//            if (status.equals("0")) {
//                return "离线";
//            }
//            if (status.equals("1")) {
//                return "在线";
//            }
//            if (status.equals("4")) {
//                return "关机";
//            }
//            return "异常1";
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "异常2";
//        }

    }





    public static String sendCmd(String imei, int high, int low, int pulse, String orderCode) {
            String sResult="";
        try {

            JSONObject obj = new JSONObject();
            obj.put("imei", imei);
            obj.put("high", high);
            obj.put("low", low);
            obj.put("pulse", pulse);

            String result = OkHttpUtil.postJsonParams(ADD_URL, obj.toString());
            log.info("设备imei：" + imei + "--》设备返回信息：" + result);

            com.alibaba.fastjson.JSONObject job = JSON.parseObject(result);
            int code=10;
            code = job.getIntValue("code");

            if(code==0){
                log.info("设备imei：" + imei + "--》命令发送成功：" );
                sResult="设备imei：" + imei + "--》命令发送成功："+result;
            }else{
                log.info("设备imei：" + imei + "--》命令发送失败，code 非0：" + result);
                sResult="设备imei：" + imei + "--》命令发送失败，code 非0：："+result;
            }


        }catch (Exception e) {
            e.printStackTrace();
            log.error("设备imei:" + imei + "--》命令发送失败B，异常抓取" + e.getMessage(), e.getMessage());
            sResult="设备imei：" + imei + "--》命令发送失败B，异常抓取："+e.getMessage();
        }

        log.info("设备imei:" + imei);
        return sResult;


    }



    public static String testGet(String imei) {

        String url = "http://www.baidu.com";
        OkHttpClient okHttpClient = new OkHttpClient();

        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.info("onFailure: ");

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                log.info("onResponse: " + response.body().string());
            }
        });


        return "";
    }


    public static void main(String[] args) {

//        ChairCmd.getImeiStatus("869300031588258");



//        ChairCmd.launcherChairs("869300031588258",50,250,2,"aaa");
        //ChairCmd.launcherChairs("869300031692100",50,250,1,"aaa");
//        ChairCmd.launcherChairs("869300031605367",50,250,1,"aaa");
//        ChairCmd.launcherChairs("869300031588258",50,250,1,"z006");
//        ChairCmd.launcherChairs("869300031605367",50,250,1,"z011");
//        ChairCmd.launcherChairs("869300031591856",50,250,4,"z000");
//        ChairCmd.launcherChairs("869300031527108",50,250,1,"z001");
//        ChairCmd.launcherChairs("869300031588571",50,250,1,"z002");
//        ChairCmd.launcherChairs("869300031634953",50,250,4,"z003");
//          ChairCmd.launcherChairs("869300031611324",50,250,1,"z004");
//        ChairCmd.launcherChairs("869300031676442",50,250,1,"z005");//
//          ChairCmd.launcherChairs("869300031588258",50,250,1,"z006");
//          ChairCmd.launcherChairs("869300031592862",50,250,4,"z007");
//        ChairCmd.launcherChairs("869300031527140",50,250,1,"z008");
//        ChairCmd.launcherChairs("869300031685401",50,250,2,"z009");
//          ChairCmd.launcherChairs("869300031692100",50,250,4,"z010");
//          ChairCmd.launcherChairs("869300031605367",50,250,1,"z011");
//        869300031583457

        ChairCmd.getImeiStatus("869300031591856");
//        ChairCmd.launcherChairs("869300031521838", 50, 250, 2, "B006");
//          ChairCmd.sendCmd("869300031690682", 50, 250, 1, "B076");





    }


}